package ufrj.safcp.view.components;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

import ufrj.safcp.tools.imagecapturing.IImageReceiver;

public class ImagePanel extends JPanel implements IImageReceiver {

	private static final long serialVersionUID = 1L;
	
	private Image image = null;
	
	private boolean stretch;

	public ImagePanel() {
		
	}

	public void paint(Graphics g) {
		super.paint(g);
		if (getImage() != null) {
			int width;
			int height;
			if (getImage() instanceof BufferedImage && !stretch)  {
				width = (int) Math.min(this.getPreferredSize().getWidth(), getBufferedImage().getWidth());
				height = (int) Math.min(this.getPreferredSize().getHeight(), getBufferedImage().getHeight());
			} else {
				width = (int) this.getPreferredSize().getWidth();
				height = (int) this.getPreferredSize().getHeight();
			}
			g.drawImage(getImage(), 0, 0, width, height, null);
		}
	}

	public void setImage(Image image) {
		this.image = image;
		this.updateUI();
	}
	
	protected BufferedImage getBufferedImage() {
		if (this.image instanceof BufferedImage) {
			return (BufferedImage) this.image;
		}
		return null;
	}

	public Image getImage() {
		return image;
	}

	public void receiveImage(Image bimg) {
		setImage(bimg);
	}

	public boolean isStretch() {
		return stretch;
	}

	public void setStretch(boolean stretch) {
		this.stretch = stretch;
	}

}